<template>
  <div class="min-h-screen bg-gray-50">
    <div class="flex">
      <!-- 右侧内容区 -->
      <div class="flex-1 p-8">
        <!-- 发件箱 -->
        <div class="inbox-container">
          <div class="flex flex-col mb-6">
            <h2 class="text-2xl font-bold">发件箱</h2>
          </div>
          <div class="flex justify-between items-center mt-2">
            <!-- 新建发件按钮 -->
            <button
              @click="openNewMail"
              class="px-4 py-2 bg-blue-500 text-white hover:bg-blue-600 !rounded-button whitespace-nowrap flex items-center gap-2"
              style="padding: 8px 16px; flex-grow: 0"
            >
              <el-icon><Message /></el-icon>
              新建发件
            </button>
          </div>
          <div class="flex justify-between items-center mt-4">
            <!-- 搜索框 -->
            <el-input
              v-model="searchQuery"
              placeholder="搜索发件人..."
              class="flex-1 mr-2"
              prefix-icon="search"
            ></el-input>

            <!-- 批量删除按钮 -->
            <button
              @click="openBatchDeleteConfirm"
              class="px-4 py-2 bg-red-500 text-white hover:bg-red-600 !rounded-button whitespace-nowrap"
              style="padding: 8px 16px"
            >
              批量删除
            </button>
          </div>
          <div class="space-y-4">
            <!-- 邮件列表 -->
            <div
              v-for="mail in sentMails"
              class="p-4 border rounded-lg cursor-pointer hover:bg-blue-100 mt-8"
              
            >           
              <div class="flex items-center justify-between">
                <div class="flex items-center gap-3" >
                  <!-- 选择框 -->
                 <input
                    type="checkbox"
                    class="mr-2"
                    @change="toggleMailSelection(mail)"
                    :checked="selectedMails.includes(mail)"
                  />
                  <div class="flex items-center gap-3 w-64" @click="showMailDetail(mail)">
                    <el-avatar :size="48" class="mr-4" >
                      {{ mail.sendAccount[0] }}
                    </el-avatar>
                    <div>
                      <div class="font-medium">发送至：{{ mail.receiveAccount }}</div>
                      <div class="text-sm text-gray-500">
                        {{ mail.title }}
                      </div>
                    </div>
                  </div>
                </div>
                <div class="text-sm text-gray-500">{{ formatDate( mail.date) }}</div>
                <!-- 单行删除按钮 -->
                <button
                  class="ml-2 delete-button"
                  @click.stop="openDeleteConfirm(mail)"
                >
                <el-icon class="delete-icon"><Delete /></el-icon>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 邮件详情弹窗 -->
    <el-dialog
      v-model="mailDetailDialogVisible"
      title="邮件详情"
      width="600px"
      destroy-on-close
    >
      <div class="space-y-6">
        <div class="flex items-start gap-4 p-4 bg-gray-50 rounded-lg">
          <el-avatar :size="48" class="mr-4" >
            {{ currentMail.sendAccount[0] }}
          </el-avatar>
          <div class="flex-1">
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-2">
                <div class="font-medium">{{ currentMail?.sendAccount }}</div>
                <div
                  v-if="currentMail?.originalReceiver"
                  class="text-sm text-gray-500"
                >
                  (与我的会话)
                </div>
              </div>
              <div class="text-sm text-gray-500">{{ currentMail?.date }}</div>
            </div>
            <div class="text-gray-600 mt-1">{{ currentMail?.title }}</div>
          </div>
        </div>
        <div class="p-4 bg-white border rounded-lg min-h-[100px]">
          {{ currentMail?.content }}
        </div>
        <div class="border-t pt-4">
          <h4 class="font-medium mb-2">回复</h4>
          <el-input
            v-model="replyForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </div>
      </div>
      <template #footer>
        <div class="flex justify-end gap-4">
          <button
            class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 !rounded-button whitespace-nowrap"
            @click="mailDetailDialogVisible = false"
          >
            关闭
          </button>
          <button
            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 !rounded-button whitespace-nowrap"
            @click="replyMail"
          >
            发送回复
          </button>
        </div>
      </template>
    </el-dialog>

    <!-- 邮件发送弹窗 -->
    <el-dialog
      v-model="mailDialogVisible"
      title="发送邮件"
      width="600px"
      destroy-on-close
    >
      <div class="space-y-4">
        <div class="flex items-start gap-4">
          <div class="w-20 text-right pt-2">发件人：</div>
          <el-input
            v-model="account"
            disabled
            placeholder="请输入您的邮箱地址"
            class="flex-1"
          />
        </div>
        <div class="flex items-start gap-4">
          <div class="w-20 text-right pt-2">收件人：</div>
          <el-input
            v-model="mailForm.receiveAccount"
            placeholder="请输入收件人账号"
            class="flex-1"
          />
        </div>
        <div class="flex items-start gap-4">
          <div class="w-20 text-right pt-2">主题：</div>
          <el-input
            v-model="mailForm.title"
            placeholder="请输入邮件主题"
            class="flex-1"
          />
        </div>
        <div class="flex items-start gap-4">
          <div class="w-20 text-right pt-2">正文：</div>
          <el-input
            v-model="mailForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入邮件内容"
            class="flex-1"
          />
        </div>
      </div>
      <template #footer>
        <div class="flex justify-end gap-4">
          <button
            class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 !rounded-button whitespace-nowrap"
            @click="mailDialogVisible = false"
          >
            取消
          </button>
          <button
            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 !rounded-button whitespace-nowrap"
            @click="sendMail"
          >
            发送
          </button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { Delete } from '@element-plus/icons-vue';
import {addEmail, getBySender,deleteEmail} from "../../../api/student/email/email";
onMounted(()=>{
  getEmail(confirmData)
})
function getEmail(data) {
  getBySender(data).then(function (response) {
    sentMails.value=response.items[0]
  })
}
function add_Email(data) {
    addEmail(data).then(function (response) {
        getEmail(confirmData)
    })
}
const account=ref(JSON.parse(localStorage.getItem("userInfo")).account)
const confirmData=({
  account:account.value,
  page:1,
  pageSize:100
})


// 日期格式化方法
const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`; // 返回 yyyy-mm-dd 格式
};

// 用户信息
let profileForm = ref({
  name: "王总监",
  title: "科技招聘总监",
  company: "未来科技有限公司",
  phone: "13800138000",
  email: "wang@future-tech.com",
  avatar:
    "https://ai-public.mastergo.com/ai/img_res/f181576e695dad80f53211028b3b7813.jpg",
});

// 发件箱数据
let sentMails = ref([]);

// 邮件详情弹窗控制
const mailDetailDialogVisible = ref(false);
const currentMail = ref(null);
const replyForm = ref({
  content: "",
});

// 显示邮件详情
const showMailDetail = (mail) => {
  currentMail.value = {
    ...mail,
    // 发件箱的消息需要调整发送者和头像为自己的信息
    sender: mail.receiver,
    senderAvatar: mail.receiverAvatar,
    // 保存原始信息用于回复
    originalReceiver: mail.receiver,
    originalReceiverAvatar: mail.receiverAvatar,
  };
  mailDetailDialogVisible.value = true;
};

// 回复邮件
const replyMail = () => {
  if (!replyForm.value.content) {
    ElMessage.error("请输入回复内容");
    return;
  }

  // 构建新的发送消息
  const newMail = {
    account:account.value,
    receiverAccount: currentMail.value.originalReceiver || currentMail.value.sender,
    title: `Re: ${currentMail.value.subject}`,
    content: replyForm.value.content,
    status:1,
    type:"个人邮件"
  };
  // 添加到发件箱
  add_Email(newMail)
  ElMessage.success("回复成功");
  mailDetailDialogVisible.value = false;
  replyForm.value.content = "";
};

// 发送新邮件
const mailForm = ref({
  title: "",
  content: "",
  sendAccount: "",
  receiveAccount: "",
});
const mailDialogVisible = ref(false);

const sendMail = () => {
  if (
    !mailForm.value.receiveAccount ||
    !mailForm.value.title ||
    !mailForm.value.content
  ) {
    ElMessage.error("请填写完整邮件信息");
    return;
  }
  // 构建新的发送消息
  const newMail = {
    sendAccount:account.value,
    receiveAccount: mailForm.value.receiveAccount,
    title: mailForm.value.title,
    status:1,
    content: mailForm.value.content,
    type:"个人邮件"
  };
  // 添加到发件箱
  add_Email(newMail)
  ElMessage.success("邮件发送成功");
  mailDialogVisible.value = false;
  // 重置表单
  mailForm.value = {
    title: "",
    content: "",
    sendAccount: "",
    receiveAccount: "",
  };
};

// 打开新建邮件弹窗
const openNewMail = () => {
  mailForm.value = {
    title: "",
    content: "",
    receiveAccount: "",
  };
  mailDialogVisible.value = true;
};

// 搜索查询
const searchQuery = ref("");



// 批量删除相关
const selectedMails = ref([]);

// 打开单行删除确认弹窗
const openDeleteConfirm = (mail) => {
  singleMailToDelete.value = mail;
  ElMessageBox.confirm("此操作不可逆，确定要删除吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteEmail([mail])
      sentMails.value = sentMails.value.filter(
        (mail) => mail.id !== singleMailToDelete.value.id
      );
      ElMessage.success("已删除邮件");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const singleMailToDelete = ref(null);

// 打开批量删除确认弹窗
const openBatchDeleteConfirm = () => {
  if (selectedMails.value.length > 0) {
    ElMessageBox.confirm("此操作不可逆，确定要删除选中的邮件吗？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        deleteEmail(selectedMails.value).then(function () {
          getEmail(confirmData)
        })
        sentMails.value = sentMails.value.filter(
          (mail) => !selectedMails.value.includes(mail)
        );
        selectedMails.value = [];
        ElMessage.success("已删除选中的邮件");
      })
      .catch(() => {
        ElMessage.info("已取消删除");
      });
  } else {
    ElMessage.warning("请选择要删除的邮件");
  }
};

// 切换邮件的选择状态
const toggleMailSelection = (mail) => {
  if (selectedMails.value.includes(mail)) {
    selectedMails.value = selectedMails.value.filter((m) => m.id !== mail.id);
  } else {
    selectedMails.value.push(mail);
  }
};
</script>

<style scoped>
.inbox-container {
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 2rem;
}

.mail-item {
  border: 1px solid #ccc;
  transition: background-color 0.3s, box-shadow 0.3s;
}

.mail-item:hover {
  background-color: #add8e6;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.time-info {
  margin-left: auto;
  text-align: right;
}

.el-input {
  width: 100%;
}

.el-button {
  margin-top: 8px;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  padding: 10px 20px;
}

.delete-icon {
  color: gray;
}

.delete-button {
  background-color: transparent;
  border: none;
  cursor: pointer;
}

</style>
